﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using Extensil.Common.CategoryHandler.Discovery;

namespace Extensil.Discovery.SharedPath
{
    public class SharedFolder :BaseProbeHandler
    {
        ProbeParamList _paramList;
        public override string[] Keys
        {
            get
            {
                return new string[] { "SharedPath", "LookupFile", "UserName", "Password" };
            }
        }
        public override bool ValidateParam(ProbeParamList paramList)
        {
            if(!paramList.ContainsName("SharedPath"))
                throw new Exception("Parameter SharedPath is required to establish connection with SharedFolder.");
            else if(String.IsNullOrEmpty(paramList["SharedPath"].Trim()))
                throw new Exception("SharedPath must be a valid shared location.");

            if(!paramList.ContainsName("LookupFile"))
                throw new Exception("Parameter LookupFile is required to establish connection with SharedFolder.");
            else if(String.IsNullOrEmpty(paramList["LookupFile"].Trim()))
                throw new Exception("LookupFile must be a valid file name.");

            return true;
        }
        public override void Connect(ProbeParamList paramList)
        {
            try
            {
                _paramList = paramList;
                ReportStatus("Connected to SharedFolder");
            }
            catch(FileNotFoundException exc)
            {
                throw new Exception("You are not authorized.");
            }
        }
        public override DiscoveryResultList Search()
        {
            ReportStatus("Searching for updates.");
            DiscoveryResultList retValue = new DiscoveryResultList();
            return retValue;
        }
        public override DiscoveryResultList Search(DateTime modifiedOrAddedSince)
        {
            return new DiscoveryResultList();
        }
        public override string DownloadPlugin(string path)
        {
            Uri url = new Uri(path);
            WebRequest request = WebRequest.Create(url);
            request.UseDefaultCredentials = true;
            WebResponse response = request.GetResponse();
            Stream fs = response.GetResponseStream() as Stream;

            string fileName = url.Segments[url.Segments.Length - 1];
            using(FileStream localfs = File.OpenWrite(fileName))
            {
                CopyStream(fs, localfs);
            }
            return fileName;
        }
        void CopyStream(Stream input, Stream output)
        {
            byte[] buffer = new byte[8 * 1024];
            int len;
            while((len = input.Read(buffer, 0, buffer.Length)) > 0)
            {
                output.Write(buffer, 0, len);
            }
        }
    }
}
